package com.bootdo.system.service.impl;

import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.dao.SysUserCacheDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.SysUserCache;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.SysUserCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @create 2021-03-02 13-51
 */
@Service
public class SysUserCacheServiceImpl implements SysUserCacheService {

    @Autowired
    private SysUserCacheDao cacheDao;

    @Autowired
    private UserDao userDao;


    @Override
    public R insertSysUserCache(SysUserCache sysUserCache) {
        UserDO user = ShiroUtils.getUser();
        UserDO userDO = userDao.get(user.getUserId());
        Long balance = Long.valueOf(userDO.getBalance());
        long price = sysUserCache.getPrice().longValue();
        if(price<=0){
            return R.error("提取金额请大于0!");
        }

        if(balance>=price){
            userDO.setBalance(String.valueOf(balance-price));
            userDao.update(userDO);
            cacheDao.insetSysUserCache(sysUserCache);

        }else {
            return R.error("账户余额不足!");
        }

        return R.ok();
    }

    @Override
    public R updateSysUserCache(SysUserCache sysUserCache) {
        sysUserCache.setUpdateTime(LocalDateTime.now().toString());
        cacheDao.updateSysUserCache(sysUserCache);
        return R.ok();
    }

    @Override
    public List<Map> selectSysUserCacheList(Query query) {
        List<Map> sysUserCaches = cacheDao.selectSysUserList(query);
        return sysUserCaches;
    }

    @Override
    public int selectUserCount(Query query) {
        return cacheDao.selectUserCount(query);
    }
}
